﻿using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace MoreExtentions
{
    public static partial class Linq
    {
        /// <summary>
        /// Clones the specified obj.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj">The obj.</param>
        /// <returns></returns>
        public static T Clone<T>(this T obj) where T : class
        {
            if (obj != null)
            {
                var formatter = new BinaryFormatter();
                var stream = new MemoryStream();

                formatter.Serialize(stream, obj);
                stream.Seek(0, SeekOrigin.Begin);

                var result = (T)formatter.Deserialize(stream);
                stream.Close();
                return result;
            }
            return default(T);
        }
    }
}